﻿using NPOI.HSSF.UserModel;
using SF.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SF.Ucenter.admin.finance
{
    public partial class finance_settlement_past : Web.UI.ManagePage
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected string action = string.Empty;
        protected string keywords = string.Empty;
        protected int state = -1;
        protected void Page_Load(object sender, EventArgs e)
        {
            this.state = Request["state"] == null ? -1 : int.Parse(Request["state"]);
            this.keywords = DTRequest.GetQueryString("keywords");
            this.action = DTRequest.GetQueryString("action");
            if (this.action == "export")
            {
                ExportData();
            }


            this.pageSize = GetPageSize(10); //每页数量
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("app_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                RptBind(" id>0" + CombSqlTxt(state,this.keywords), "id desc");
            }
        }

        #region 导出数据

        private void ExportData() 
        {
            string strWhere = " id>0" + CombSqlTxt(state, this.keywords) + " order by id desc";
            BLL.sf_finance_settlement bll = new BLL.sf_finance_settlement();
            System.Data.DataSet dsList = bll.GetList(strWhere);

            Hashtable hsColumns = new Hashtable();
            hsColumns.Add("id","编号");
            hsColumns.Add("settlement_num", "结算单编号");
            hsColumns.Add("user_name", "经手人");
            hsColumns.Add("total_amount", "合计");
            hsColumns.Add("received", "已收");
            hsColumns.Add("not_received", "未收");
            hsColumns.Add("state", "状态");
            hsColumns.Add("状态","状态");
            hsColumns.Add("create_time","生成时间");

            dsList.Tables[0].Columns.Add("状态");
            foreach (System.Data.DataRow r in dsList.Tables[0].Rows)
            {
                r["状态"] = r["state"].ToString() == "0" ? "未完成收费" : "已完成收费";
            }
            dsList.Tables[0].Columns.Remove("state");

            //移除主键字段            
            foreach (System.Data.DataColumn col in dsList.Tables[0].Columns) 
            {
                col.ColumnName = hsColumns[col.ColumnName].ToString();
            }

            dsList.Tables[0].Columns.RemoveAt(0);
            dsList.Tables[0].TableName = "财务结算单";
            HSSFWorkbook workbook = NPOIExcelHelper.GridToExcelByNPOI(dsList);
            DownLoad(workbook,"财务结算单");
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="hssfWorkbook">excel工作簿</param>
        /// <param name="fileName">文件名</param>
        private void DownLoad(HSSFWorkbook hssfWorkbook, string fileName)
        {
            using (MemoryStream memoryStram = new MemoryStream())
            {
                //把工作簿写入到内存流中
                hssfWorkbook.Write(memoryStram);
                //设置输出编码格式
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                //设置输出流
                Response.ContentType = "application/octet-stream";
                //防止中文乱码
                fileName = HttpUtility.UrlEncode(fileName);
                //设置输出文件名
                Response.AppendHeader("Content-Disposition", "filename=" + fileName + ".xls");
                //输出
                Response.BinaryWrite(memoryStram.GetBuffer());
            }
        } 

        /// <summary>
        /// 取得网站根目录的物理路径
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            string AppPath = "";
            HttpContext HttpCurrent = HttpContext.Current;
            if (HttpCurrent != null)
            {
                AppPath = HttpCurrent.Server.MapPath("~");
            }
            else
            {
                AppPath = AppDomain.CurrentDomain.BaseDirectory;
                if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success)
                    AppPath = AppPath.Substring(0, AppPath.Length - 1);
            }
            return AppPath;
        }

        #endregion

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            this.ddlStatus.SelectedValue = this.state.ToString();

            this.page = DTRequest.GetQueryInt("page", 1);
            txtKeywords.Text = this.keywords;
            BLL.sf_finance_settlement bll = new BLL.sf_finance_settlement();
            this.rptList.DataSource = bll.GetList(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
            this.rptList.DataBind();


            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = string.Format("finance_settlement_past.aspx?state={0}&keywords={1}&page={2}", ddlStatus.SelectedValue, this.keywords, "__id__");
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(int state,string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and (settlement_num like  '%" + _keywords + "%' or user_name like '%" + _keywords + "%' or create_time like '%" + _keywords + "%')");
            }

            if (state > -1) 
            {
                strTemp.Append(" and state = " + state);
            }

            return strTemp.ToString();
        }
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("finance_page_size", "DTcmsPage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string url = string.Format("finance_settlement_past.aspx?state={0}&keywords={1}", ddlStatus.SelectedValue, this.txtKeywords.Text);
            Response.Redirect(url);
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("finance_page_size", "DTcmsPage", _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(Utils.CombUrlTxt("finance_settlement_past.aspx", "keywords={0}", this.keywords));
        }

        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e) 
        {
            string url = string.Format("finance_settlement_past.aspx?state={0}&keywords={1}", ddlStatus.SelectedValue, this.keywords);
            Response.Redirect(url);
        }
    }
}